import { MENU_ACTION, SET_MENU, GET_MENU } from '@/utils/Const';
import { getMenuApi } from '@/api/system.api';
import { asyncRoutes } from '@/router';
import { routesToMap, mappingRoutes } from '@/utils/tools';

export default {
	namespaced : true,
	// 无法直接给state赋值,所以必须绑定key
	state : {
		value : []
	},
	getters : {
		[GET_MENU] (state) {
			return state.value;
		}
	},
	mutations : {
		[SET_MENU] (state, payload) {
			state.value = payload;
		}
	},
	actions : {
		async [MENU_ACTION] ({ commit }) {
			try {
				let res = await getMenuApi();
				// 路由转map对象
				const routesMap = routesToMap(asyncRoutes);
				// 接口路由映射
				const routes = mappingRoutes(routesMap, res);
				// 首页转换子路由
				let dashboard = routesMap[''];
				routes[0].children = [dashboard];
				return new Promise((resolve) => {
					commit(SET_MENU, routes);
					resolve(routes);
				});
			} catch (e) {
				console.log('err', e);
			}
		}
	}
};
